<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 拜访接口
 */
class Visit extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['createcomplaint'];

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

         $this->visit=model('admin/customer/Visit');
        $this->CustomerCustomers=model('admin/customer/Customers');

    }

    /**拜访客户
     * @param $customers_id
     * @param $lng
     * @param $lat
     * @param $sign_time
     * @param $address
     * @param null $desc
     * @param null $images
     */
    public function addEditVisit($id,$customers_id,$lng,$lat,$sign_time,$address,$desc=null,$images=null){
        $where['id']=['=',$customers_id];
        if( $customerDetails= $this->CustomerCustomers
            ->get($where)){

            if($lng=='' || $lat==''){
                $this->error('拜访经纬度必须选择');
            }
            if($sign_time==''){
                $this->error('拜访时间必须选择');
            }
            if($address==''){
                $this->error('签到地址必须填写');
            }
            $data=['user_id'=>$this->auth->id,'customer_customers_id'=>$customers_id,'lng'=>$lng,'lat'=>$lat,'sign_time'=>strtotime($sign_time),'address'=>$address,'desc'=>$desc,'images'=>$images];

            if(!$id){
               if($data['desc']!=null && $data['images']!=''){
                $data['status']='正常';
               }else{
                   $data['status']='异常';
               }
                $this->visit->save($data);
            }else{
              if($visitInfo= $this->visit->get(['id'=>$id])){

                  if($data['desc']!=null && $data['images']!=''){
                      $data['status']='正常';
                  }else{
                      $data['status']='异常';
                  }
                  $this->visit->where('id',$id)->update($data);
              }else{
                  $this->error('未找到拜访记录');
              }

            }

            $this->success('拜访提交成功');

        }else{
            $this->error('客户信息不存在');
        }



    }

    /**
     * 拜访记录
     */
        public function visitList($page=1,$limit=10,$customers_id=null,$status='全部',$day=null,$month=null,$start_time=null,$end_time=null,$user_id=null){
         if($user_id!=null){
             $where['v.user_id']=['=',$user_id];
         }else{
             $where['v.user_id']=['=',$this->auth->id];
         }

             if($customers_id!=null){
                 $where['v.customer_customers_id']=['=',$customers_id];
             }
             if($status!='全部'){
                 $where['v.status']=['=',$status];
             }
            if($day!=null){
                $where['sign_time']=['between',[strtotime($day),strtotime($day." 23:59:59")]];
            }
            if($month!=null){
                $newYearMonth= implode("-",$month);
                $newMonth = $newYearMonth[1]; // 当前月份
                $newYear = $newYearMonth[0]; // 当前年份

                $nextMonthFirstDay = strtotime("+1 month", mktime(0, 0, 0, $newMonth, 1, $newYear));

                $lastDayOfThisMonth = strtotime("-1 day", $nextMonthFirstDay);

                $where['sign_time']=['between',[strtotime($month." -01"),strtotime($lastDayOfThisMonth)]];

            }
            if($start_time!=null && $end_time!=null){
                $where['sign_time']=['between',[strtotime($start_time),strtotime($end_time. "23:59:59")]];
            }

            // dump($where);
            //customer/Customers
            $evaluateList=$this->visit
                ->alias('v')
                ->join('__USER__ u ','v.user_id= u.id')
                ->join('__CUSTOMER_CUSTOMERS__ c ','v.customer_customers_id= c.id')
                ->where($where)
                ->field('v.*,u.username,u.avatar,c.avatar as customeravatar,c.name')
                ->order('v.createtime desc')->paginate($limit);
             foreach ($evaluateList as $key=>$value){
                 $evaluateList[$key]['createtime']=date('Y-m-d H:i:s',$value['createtime']);
                 $evaluateList[$key]['sign_time']=date('Y-m-d H:i:s',$value['sign_time']);
             }
             $this->success('OK',$evaluateList);
        }

    /**
     * 拜访客户详情
     */
        public function visitDetails($id=null){
//           $where=[];
//            if($id!=null){
                $where['id']=['=',$id];
//            }
//            if($day!=null){
//               $where['sign_time']=['between',[strtotime($day),strtotime($day." 23:59:59")]];
//            }

           if($visitInfo=$this->visit->get($where)){
               if($visitInfo['images']!=''){
                   $visitInfo['images']=explode(",",$visitInfo['images']);
               }else{
                   $visitInfo['images']=[];
               }

               $visitInfo['customername']=$this->CustomerCustomers->where('id',$visitInfo['customer_customers_id'])->value('name');


            //   $visitInfo['sign_time']=date('Y-m-d H:i:s',$visitInfo['sign_time']);
               $this->success('OK',$visitInfo);

           }else{

               $this->error('拜访记录不存在');
           }

        }

        /**
         * 拜访统计
         */

        public function visitStatistics($customers_id=null,$day=null,$month=null,$start_time=null,$end_time=null){
           $where['user_id']=['=',$this->auth->id];
           if($customers_id!=null){
               $where['customer_customers_id']=['=',$customers_id];
           }
           if($day!=null){
               $where['sign_time']=['between',[strtotime($day),strtotime($day." 23:59:59")]];
           }
           if($month!=null){
              $newYearMonth= implode("-",$month);
               $newMonth = $newYearMonth[1]; // 当前月份
               $newYear = $newYearMonth[0]; // 当前年份

               $nextMonthFirstDay = strtotime("+1 month", mktime(0, 0, 0, $newMonth, 1, $newYear));

               $lastDayOfThisMonth = strtotime("-1 day", $nextMonthFirstDay);

               $where['sign_time']=['between',[strtotime($month." -01"),strtotime($lastDayOfThisMonth)]];

           }
           if($start_time!=null && $end_time!=null){
               $where['sign_time']=['between',[strtotime($start_time),strtotime($end_time. "23:59:59")]];
           }

          $data['all']=$this->visit->where($where)->count();
          $data['yichang']=$this->visit->where($where)->where('status','异常')->count();
         $data['zhengchang']=$this->visit->where($where)->where('status','正常')->count();
         $this->success('OK',$data);

        }


}
